﻿using UnityEngine;

namespace Nomo.UnityCoreModule
{
    /// <summary>
    /// 为 <see cref="UnityEngine.Collider2D"/> 类的实例提供扩展方法。
    /// </summary>
    public static class Collider2DExtension
    {
        /// <summary>
        /// 返回二维多边形碰撞器在世界坐标下的内部随机一点。
        /// </summary>
        /// <param name="collider2D">多边形碰撞器。</param>
        /// <returns>多边形碰撞器在世界坐标下的内部随机一点。</returns>
        public static Vector3 RandomInside(this PolygonCollider2D collider2D)
        {
            var bounds = collider2D.bounds;
            var rect   = Rect.zero;
            rect.size   = bounds.size;
            rect.center = bounds.center;

            Vector3 randomInside;
            var     points   = collider2D.points;
            var     position = collider2D.transform.position;
            do
            {
                randomInside = rect.RandomInside();
            } while (!ContainmentHelper.Contains(randomInside - position, points));
            randomInside.z = position.z;
            return randomInside;
        }

        /// <summary>
        /// 缩放多边形碰撞器。
        /// </summary>
        /// <param name="collider2D">多边形碰撞器。</param>
        /// <param name="scale">缩放值。</param>
        public static void Scale(this PolygonCollider2D collider2D, float scale)
        {
            var points = collider2D.points;
            var offset = collider2D.offset;
            for (var i = 0; i < points.Length; i++)
            {
                points[i] = Vector2.LerpUnclamped(offset, points[i] + offset, scale) - offset;
            }
            collider2D.points = points;
        }
    }
}
